#ifndef BUFFER_H_
#define BUFFER_H_

#include "stddef.h"
#include "string.h"

class Buffer
{
public:
	Buffer(size_t size):m_size(size), m_currentSize(0)
	{
		m_buffer = new unsigned char[m_size];
	}

	Buffer(const Buffer& rhs):m_size(rhs.m_size),m_currentSize(rhs.m_currentSize)
	{
		m_buffer = new unsigned char[m_size];
		memcpy(m_buffer,rhs.m_buffer,m_currentSize);	
	}

	// 如果传入的size超过rhs的存储量，则只复制rhs存储量的数据
	Buffer(const Buffer& rhs, size_t size)
	{
		if (size > rhs.m_currentSize)
			size = rhs.m_currentSize;
		m_size = size;
		m_currentSize = size;
		m_buffer = new unsigned char[size];
		memcpy(m_buffer, rhs.m_buffer, size);
	}

	Buffer& operator=(const Buffer& rhs)
	{
		delete[] m_buffer;
		m_size = rhs.m_size;
		m_currentSize = rhs.m_currentSize;
		m_buffer = new unsigned char[m_size];	
		memcpy(m_buffer,rhs.m_buffer,m_currentSize);
		return (*this);
	}

	~Buffer()
	{
		delete[] m_buffer;	
	}

	void Empty()
	{
		m_currentSize = 0;
	}

	inline const unsigned char* GetBuffer() const
	{return m_buffer;}

	size_t Read(void* buffer, size_t readSize)
	{
		if (readSize > m_currentSize)
			readSize = m_currentSize;
		if (NULL != buffer)
			memcpy(buffer, m_buffer, readSize);
		m_currentSize -= readSize;
		memmove(buffer, (unsigned char*)buffer + readSize, m_currentSize);
		return readSize;
	}

	size_t Write(const void* buffer, size_t writeSize)
	{
		if (m_size - m_currentSize < writeSize )
		{
			m_size *= 2;
			unsigned char* tmp = new unsigned char[m_size];
			memcpy(tmp, m_buffer, m_currentSize);
			delete[] m_buffer;
			m_buffer = tmp;
		}
		memcpy(m_buffer + m_currentSize, buffer, writeSize);
		m_currentSize += writeSize;
		return writeSize;
	}

	size_t Write(Buffer& buf, size_t writeSize)
	{
		if (writeSize > buf.m_currentSize)
			writeSize = buf.m_currentSize;
		
		this->Write(buf.m_buffer, writeSize);

		buf.Read(NULL, writeSize);

		return writeSize;
	}

	int Size() const
	{return m_currentSize;}
private:
	unsigned char* m_buffer;
	size_t m_size; // max size
	size_t m_currentSize; // now size
};

#endif
